﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Threading;
using System.ServiceModel.Description;


namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "WCF服务端";
            // 服务器基址   
            Uri baseAddress = new Uri("http://localhost:1378/services");
            // 声明服务器主机   
            using (ServiceHost host = new ServiceHost(typeof(MyService), baseAddress))
            {
                // 添加绑定和终结点   
                // tcp绑定支持会话   
                NetTcpBinding binding = new NetTcpBinding();
                binding.Security.Mode = SecurityMode.None;
                host.AddServiceEndpoint(typeof(IService), binding, "net.tcp://localhost:1211/rr");
                // 添加服务描述   
                host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
                try
                {
                    // 打开服务   
                    host.Open();
                    Console.WriteLine("服务已启动。");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.ReadKey();
            }
        }
    }

    public interface ICallback
    {
        [OperationContract(IsOneWay = true)]
        void CallClient(int v);
    }

    [ServiceContract(Namespace = "MyNamespace",
        CallbackContract = typeof(ICallback), /* 标注回调协定 */
        SessionMode = SessionMode.Required /* 要求会话 */
        )]
    public interface IService
    {
        // 会话从调用该操作启动   
        [OperationContract(IsOneWay = true, /* 必须 */
            IsInitiating = true, /* 启动会话 */
            IsTerminating = false)]
        void CallServerOp();

        // 调用该操作后，会话结束   
        [OperationContract(IsOneWay = true, /* 使用回调，必须为OneWay */
            IsTerminating = true, /* 该操作标识会话终止 */
            IsInitiating = false)]
        void End();
    }

    public class MyService : IService, IDisposable
    {
        private ICallback m_cb;
        private Timer timer = null;//计时器，定时干活   
        Random rand = null;//生成随机整数   

        public void CallServerOp()
        {
            this.m_cb = OperationContext.Current.GetCallbackChannel<ICallback>();
            rand = new Random();
            // 生成随整数，并回调到客户端   
            // 每隔3秒生成一次   
            timer = new Timer((obj) => m_cb.CallClient(rand.Next()), null, 10, 3000);

        }

        public void Dispose()
        {
            timer.Dispose();
            Console.WriteLine("{0} - 服务实例已释放。", DateTime.Now.ToLongTimeString());
        }


        public void End()  //结束   
        {
            Console.WriteLine("会话即将结束。");
        }
    }

}
